/**
 * 遍历树，但是非末级节点的触发after
 * @param tree 树
 * @param {function} callback callback(accumulator, currentValue)
 * @param initValue 初始值
 * @returns {*}
 */
const treeReduce = function treeReduce(tree, callback, initValue) {
    let rel = initValue;

    if (!tree || tree.length === 0) {
        return rel;
    }

    tree.forEach((node, index) => {
        rel = callback(rel, node, false, index, tree);

        if (node?.children?.length > 0) {
            rel = treeReduce(node?.children, callback, rel);
        }

        if (!node.isLeaf) {
            rel = callback(rel, node, true, index, tree);
        }
    });

    return rel;
};

/**
 * 遍历树，但是非末级节点的不触发after
 * @param tree
 * @param callback
 * @param initValue
 * @returns {*}
 */
const treeReduceWithoutAfter = function treeReduceWithoutAfter(tree, callback, initValue) {
    return treeReduce(
        tree,
        (accumulator, node, isAfterTrigger, index, treeNodes) =>
            isAfterTrigger ? accumulator : callback(accumulator, node, false, index, treeNodes),
        initValue
    );
};

export default treeReduce;
export { treeReduceWithoutAfter };
